const util = require('./util.js')
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database();
const _ = db.command
const aDayMsec = 1000 * 60 * 60 * 24;

function getDutyList(userToken, dateInterval) {
  const todayZeroPointTimestamp = util.getTodayZeroPointTimestamp();
  const createTimestampShouldValue = todayZeroPointTimestamp - (dateInterval - 1) * aDayMsec + '';
  return new Promise((resolve, reject) => {

    db.collection('dutyList').where({
      createTimestamp: _.eq(createTimestampShouldValue),
      userToken: userToken
    }).orderBy('createTimestamp', 'asc').get().then(res => {
      resolve(res.data);
    });

  });
}

function sort(data) {
  data.sort(function (last, next) {
    return last.createTimestamp * 1 - next.createTimestamp * 1;
  });
}

// 云函数入口函数
exports.main = async (event, context) => {
  const { userToken } = event;
  const p_all = Promise.all([
    getDutyList(userToken, 2),
    getDutyList(userToken, 4),
    getDutyList(userToken, 7),
    getDutyList(userToken, 14),
    getDutyList(userToken, 21),
    getDutyList(userToken, 30),
    getDutyList(userToken, 60),
    getDutyList(userToken, 90)
  ]);
  return new Promise((resolve, reject) => {
    const data = { 
      msg: 'ok',
      status: 0,
      data: []
     };
     p_all.then(ress => {
       ress.forEach(res => {
        data.data = data.data.concat(res);  
       });
       sort(data.data);
       resolve(data);
     });

  });
}